/*
 * pmod_enc.c
 *
 *  Created on: Mar 10, 2015
 *  Author: 	Abhishek Malik
 *
 *  This is my second most honest attempt at writing a thread safe driver.
 *  This driver reads in the value of the rotary encoder.
 */

	// Rotary Values
	// ENC_SWT		ENC_BTN		ENC_B		ENC_A
	// 		0			  0			0			1		-- Counter clockwise
	//		0			  0			1			0		-- Clockwise
	// 		0			  1			1			1		-- Button Press
	// 		1			  0			1			1		-- Switch Flip
	//

#include "pmod_enc.h"

/**
 * This function reads in the rotary encoder value and then sends it across to the
 * calling function.
 */
int read_In_Gpio_ENC(XGpio * GpioInst){
	// declaring all the variables used in this function
	int i;
	int arr[2];
	int count_a=0,count_c=0,count_z=0,count_t=0;
	// reading in the values
	// since in order to get any kind of reliability in the valuesis a tough job
	// the values are first read in from the GPIO and then once they are read in
	// the function makes sure that the values are actually reliable.

	for(i=0;i<5;i++){
		arr[i] = XGpio_DiscreteRead(GpioInst, 1);
		// 7 - 0111 means that the button has been pressed
		if(arr[i] == 7){
			return	but_press;
		}
		// 11 - 1011 means that the switch has been flipped high
		else if(arr[i] == 11){
			return	sw_press;
		}
		// 1 - 0001 counter clockwise motion
		else if(arr[i] == 1){
			count_a++;
		}
		// 2 - 0010 clockwise motion
		else if(arr[i] == 2){
			count_c++;
		}
		// 0 - 0000 proably noise
		else if (arr[i] == 0){
			count_z++;
		}
		// 3 - 0011 nothing happening on the rotary encoder
		else if(arr[i] == 3){
			count_t++;
		}
	}
	// making sure that there was a clockwise movement
	if(count_c>4){
		for (i=0;i<5;i++)
			arr[i] = 0;
		return clock;
	}
	// making sure of an anticlockwise movement
	else if(count_a>4){
		for (i=0;i<5;i++)
			arr[i] = 0;
		return aclock;
	}
	return 0;
}
